---------------------------------------------------------------
-- @Description：         read/write Memdb
---------------------------------------------------------------
local skynet = require "skynet"
require "skynet.manager"
local log = require "sky_log"
local lua_memdb = require "lua_memdb"
local serpent = require "serpent"

local M = {
    config_bak = {},
    memdb_connect_t = {},
}

--============================= MSG =============================--
function M:get_money(platid, user_id)
    if not tonumber(platid)
    or not tonumber(user_id)
    or not self.memdb_connect_t[tonumber(platid)] then
        log.error("get_money error! platid="..(platid or "nil").."  user_id="..(user_id or "nil")
            .." self.memdb_connect_t="..serpent.block(self.memdb_connect_t)) 
        return 
    end

    local c = self.memdb_connect_t[tonumber(platid)]
    local total_record = c:get_user_data(tostring(user_id))
    --log.info("total_record=", total_record)

    local money
    if total_record and (type(total_record)=='string') and total_record~='' then
        money = string.match(total_record, "money:(%d+)")
    else
        self:connect_memdb(self.config_bak[tonumber(platid)])
        --连接断开了就再连接并更新一次
        local _c = self.memdb_connect_t[tonumber(platid)]
        local _total_record = _c:get_user_data(tostring(user_id))
        if _total_record and (type(_total_record)=='string') and _total_record~='' then 
            money = string.match(_total_record, "money:(%d+)")
        else
            log.error("memdb get_money error! ", total_record)
        end
    end

    return tonumber(money)
end

function M:update_money(platid, user_id, money)
    if not tonumber(platid)
    or not tonumber(user_id)
    or not self.memdb_connect_t[tonumber(platid)] 
    or not tonumber(money) then
        log.error("update_money error! platid="..(platid or "nil").."  user_id="..(user_id or "nil")
            .." money="..(money or "nil").." self.memdb_connect_t="..serpent.block(self.memdb_connect_t)) 
        return 
    end

    local c = self.memdb_connect_t[tonumber(platid)]
    local memdb_ret = c:update_user_money(user_id, money)
    --log.info("memdb_ret=", memdb_ret)

    if memdb_ret==-1 then 
        if self.config_bak[tonumber(platid)] then
            self:connect_memdb(self.config_bak[tonumber(platid)])
            --连接后再更新
            local _c = self.memdb_connect_t[tonumber(platid)]
            local ret = _c:update_user_money(user_id, money)
            if ret<0 then
                log.error("update_money error!")
            end
        end
    end
end

function M:tarneeb_reset_user_money(platid, user_id, money, wmode)
    if not tonumber(platid)
    or not tonumber(user_id)
    or not self.memdb_connect_t[tonumber(platid)]
    or not tonumber(money)
    or not tonumber(wmode) then
        log.error("tarneeb_reset_user_money error! platid="..(platid or "nil").."  user_id="..(user_id or "nil")
            .." money="..(money or "nil").." wmode="..(wmode or "nil")
            .." self.memdb_connect_t="..serpent.block(self.memdb_connect_t)) 
        return 
    end

    local c = self.memdb_connect_t[tonumber(platid)]
    local memdb_ret = c:tarneeb_reset_user_money(user_id, money, wmode)
    if memdb_ret==-1 then 
        if self.config_bak[tonumber(platid)] then
            self:connect_memdb(self.config_bak[tonumber(platid)])
            --连接后再更新
            local _c = self.memdb_connect_t[tonumber(platid)]
            local ret = _c:tarneeb_reset_user_money(user_id, money, wmode)
            if ret<0 then
                log.error("tarneeb_reset_user_money error!")
            end
        end
    end
end

function M:connect_memdb(config)
    local ip = config.mem_db_server_ip
    local port = tonumber(config.mem_db_server_port)

    if not ip
    or not port then 
        log.error("connect_memdb error! ip=", (ip or "nil").." port="..(port or "nil"))
    end

    local c = lua_memdb.create_memdb_client()
    local ret = c:connect_memdb(ip, port)
    if ret==0 then
        self.memdb_connect_t[tonumber(config.plat_id)] = c
        self.config_bak[tonumber(config.plat_id)] = config
        log.warning("connect plat_id ["..config.plat_id.."] memdb success=", self.memdb_connect_t[tonumber(config.plat_id)])
    else
        log.error("connect plat_id ["..config.plat_id.."] memdb error!")
    end
end

--============================= Init =============================--
function  M:init_by_config(config)
    --log.info("memdb init_by_config=", config)
    if not tonumber(config.plat_id) then
        log.error("memdb connect error: no plat_id!")
        return
    end

    self:connect_memdb(config)
end

skynet.start(function ()
    skynet.dispatch("lua", function(session, address, cmd, ...)
        local f = M[cmd]
        if f then
            skynet.ret(skynet.pack(f(M, ...)))
        else
            error(string.format("Unknown command %s", tostring(cmd)))
        end
    end)

    skynet.register(".memdb")
end)

return M